/**
 * ReportGear(2011)
 */
package net.abbp.report.view.cell.editor;

import java.awt.event.ActionEvent;

import javax.swing.AbstractAction;

import net.abbp.report.context.ReportContext;
import net.abbp.report.model.ReportModel;
import net.abbp.report.view.GridView;
import net.abbp.report.view.grid.Grid;

import com.reportgear.report.view.grid.selection.GridSelection;
import com.reportgear.report.view.grid.selection.Selection;

/**
 * 单元格编辑操作
 * 
 * @version 1.0 2011-6-4
 * @author <a herf="lexloo@gmail.com">lexloo</a>
 * @since Report 1.0
 */
public class CellEditAction extends AbstractAction {
    private static final long serialVersionUID = 831489367494183697L;
    // 元素对象类
    private Class<?> cellElementClazz;

    public CellEditAction(String name, Class<?> cellElementClazz) {
        super(name);

        this.cellElementClazz = cellElementClazz;
    }

    public void actionPerformed(ActionEvent e) {
        GridView gridView = ReportContext.INSTANCE.getCurrentView();
        if (gridView == null) {
            return;
        }

        GridSelection gridSel = gridView.getGridSelection();
        Grid grid = gridView.getGrid();
        if (grid.isCellSelectable()) {
            try {
                Selection sel = gridSel.getEditSelection();
                ReportModel report = gridView.getReportModel();

                Object cellElement = report.getCell(sel).getValue();
                // 单元格对象为空或单元格类与新类不相同时，设置值为新类实例
                if ((cellElement == null) || (cellElementClazz != cellElement.getClass())) {
                    report.setCellValue(sel, cellElementClazz.newInstance());
                }
                grid.startEditing();
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    }
}
